import vue from 'vue'
import loadingComponent from './toastLoding.vue'
// 返回一个 扩展实例构造器
var countopen = 0
const LodingConstructor = vue.extend(loadingComponent)
var loadingDom = null
export const showLoading = type => {
  var loadingElem = document.querySelector('#zh-loading')
  if (loadingElem === null) {
    countopen += 1
    if (countopen > 1) {
      countopen = 0
      return false
    }
    loadingDom = new LodingConstructor({
      el: document.createElement('div'),
      data() {
        return {
          showWrap: false, // 是否显示组件
          showContent: false // 作用:在隐藏组件之前,显示隐藏动画
        }
      }
    })
    document.body.appendChild(loadingDom.$el)
    if (type === 'open') {
      loadingDom.showWrap = true
    }
  }

  if (type === 'close') {
    countopen -= 1
    if (countopen < 0) {
      countopen = 0
    }
    loadingDom.showWrap = false
  }
}

// 注册为全局组件的函数
export const registryToast = () => {
  // 将组件注册到 vue 的 原型链里去,
  // 这样就可以在所有 vue 的实例里面使用 this.$toast()
  // vue.prototype.$toast = showToast
  vue.prototype.$loading = showLoading
  vue.prototype.$loading['open'] = () => {
    return showLoading('open')
  }
  vue.prototype.$loading['close'] = () => {
    return showLoading('close')
  }
}
export function hideLoading() {
  return showLoading('close')
}
